<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="订单号">
          <el-input v-model="queryParams.orderId" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="[status, info] in Object.entries(statusMap)"
              :key="status"
              :label="info.text"
              :value="status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单标签页 -->
    <el-card class="tabs-container">
      <el-tabs v-model="activeTab" tab-position="top" style="font-size: 20px; zoom:1.2;">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待支付" name="pending"></el-tab-pane>
        <el-tab-pane label="已支付" name="paid"></el-tab-pane>
        <el-tab-pane label="待发货" name="to_ship"></el-tab-pane>
        <el-tab-pane label="已发货" name="shipped"></el-tab-pane>
        <el-tab-pane label="超时未发货" name="timeout_ship"></el-tab-pane>
        <el-tab-pane label="超时未收货" name="timeout_receive"></el-tab-pane>
        <el-tab-pane label="售后中" name="after_sale"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
        <el-tab-pane label="已关闭" name="closed"></el-tab-pane>
      </el-tabs>
      <div style="margin-top: 32px;">
        <div v-if="filteredOrders.length > 0">
          <el-table
            v-loading="loading"
            :data="filteredOrders"
            style="width: 100%"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="订单号" prop="orderId" width="180" show-overflow-tooltip>
              <template #default="{ row }">
                <el-button type="text" @click="handleViewDetail(row.orderId)">
                  {{ row.orderId }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="商品信息" min-width="300">
              <template #default="{ row }">
                <div v-for="(item, index) in row.items" :key="index" class="order-item">
                  <div class="item-info">
                    <div class="item-name">{{ item.productName }}</div>
                    <div class="item-spec">{{ item.specs }}</div>
                    <div class="item-price">¥{{ item.price }} x {{ item.quantity }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="买家" prop="buyerName" width="120" />
            <el-table-column label="实付金额" prop="totalAmount" width="120">
              <template #default="{ row }">
                <span class="price">¥{{ row.totalAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="订单状态" prop="status" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button 
                  v-if="row.status === 'pending'" 
                  type="primary" 
                  size="small" 
                  @click="handleConfirmOrder(row.orderId)"
                >
                  确认订单
                </el-button>
                <el-button 
                  v-if="row.status === 'pending'" 
                  type="danger" 
                  size="small" 
                  @click="handleCancelOrder(row.orderId)"
                >
                  取消订单
                </el-button>
                <el-button 
                  v-if="row.status === 'paid' || row.status === 'to_ship'" 
                  type="success" 
                  size="small" 
                  @click="handleShipOrder(row.orderId)"
                >
                  发货
                </el-button>
                <el-button 
                  type="primary" 
                  size="small" 
                  plain
                  @click="handleViewDetail(row.orderId)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="handlePagination"
          />
        </div>
        <div v-else class="orders-empty">
          <div v-if="loading">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else>
            暂无订单，再接再厉
          </div>
        </div>
      </div>
    </el-card>
  </div>

  <!-- 发货对话框 -->
  <el-dialog
    v-model="shipDialogVisible"
    title="订单发货"
    width="500px"
    @close="resetShipForm"
  >
    <el-form
      ref="shipFormRef"
      :model="shipForm"
      :rules="shipFormRules"
      label-width="100px"
    >
      <el-form-item label="物流公司" prop="logisticsCompany">
        <el-select v-model="shipForm.logisticsCompany" placeholder="请选择物流公司">
          <el-option label="顺丰速运" value="SF" />
          <el-option label="中通快递" value="ZTO" />
          <el-option label="圆通速递" value="YTO" />
          <el-option label="韵达快递" value="YD" />
          <el-option label="申通快递" value="STO" />
          <el-option label="邮政快递" value="EMS" />
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号" prop="trackingNumber">
        <el-input v-model="shipForm.trackingNumber" placeholder="请输入物流单号" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="shipForm.remark"
          type="textarea"
          placeholder="请输入备注信息（选填）"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="shipSubmitting" @click="submitShipForm">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrders, updateOrderStatus, cancelOrder } from '@/api/orders'

const router = useRouter()
const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const selectedOrders = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderId: '',
  status: '',
  dateRange: []
})

// 订单标签
const activeTab = ref('all')

// 订单状态映射
const statusMap = {
  pending: { type: 'warning', text: '待支付' },
  paid: { type: 'primary', text: '已支付' },
  to_ship: { type: 'success', text: '待发货' },
  shipped: { type: 'info', text: '已发货' },
  completed: { type: 'success', text: '已完成' },
  closed: { type: 'danger', text: '已关闭' },
  timeout_ship: { type: 'danger', text: '超时未发货' },
  timeout_receive: { type: 'danger', text: '超时未收货' },
  after_sale: { type: 'warning', text: '售后中' }
}

// 获取状态类型
const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status]?.text || status
}

// 过滤后的订单列表
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orderList.value
  }
  return orderList.value.filter(order => order.status === activeTab.value)
})

// 获取订单列表
const getOrderList = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      startDate: queryParams.dateRange?.[0],
      endDate: queryParams.dateRange?.[1]
    }
    delete params.dateRange

    const res = await getOrders(params)
    orderList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getOrderList()
}

// 重置查询
const resetQuery = () => {
  queryParams.orderId = ''
  queryParams.status = ''
  queryParams.dateRange = []
  handleQuery()
}

// 刷新列表
const refreshList = () => {
  getOrderList()
}

// 查看详情
const handleViewDetail = (orderId) => {
  router.push(`/orders/detail/${orderId}`)
}

// 确认订单
const handleConfirmOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确认要接受此订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await updateOrderStatus(orderId, 'processing')
    ElMessage.success('订单已确认')
    getOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认订单失败:', error)
      ElMessage.error('确认订单失败')
    }
  }
}

// 取消订单
const handleCancelOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确认要取消此订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    })
    
    await cancelOrder(orderId)
    ElMessage.success('订单已取消')
    getOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getOrderList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getOrderList()
}

// 发货对话框相关数据
const shipDialogVisible = ref(false)
const shipSubmitting = ref(false)
const currentOrderId = ref('')
const shipFormRef = ref(null)
const shipForm = ref({
  logisticsCompany: '',
  trackingNumber: '',
  remark: ''
})

// 发货表单验证规则
const shipFormRules = {
  logisticsCompany: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNumber: [
    { required: true, message: '请输入物流单号', trigger: 'blur' },
    { min: 5, max: 32, message: '物流单号长度在 5 到 32 个字符', trigger: 'blur' }
  ]
}

// 处理发货
const handleShipOrder = (orderId) => {
  currentOrderId.value = orderId
  shipDialogVisible.value = true
}

// 重置发货表单
const resetShipForm = () => {
  if (shipFormRef.value) {
    shipFormRef.value.resetFields()
  }
  shipForm.value = {
    logisticsCompany: '',
    trackingNumber: '',
    remark: ''
  }
  currentOrderId.value = ''
  shipSubmitting.value = false
}

// 提交发货表单
const submitShipForm = async () => {
  if (!shipFormRef.value) return
  
  await shipFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        shipSubmitting.value = true
        await updateOrderStatus(currentOrderId.value, 'shipped', {
          logisticsCompany: shipForm.value.logisticsCompany,
          trackingNumber: shipForm.value.trackingNumber,
          remark: shipForm.value.remark
        })
        ElMessage.success('发货成功')
        shipDialogVisible.value = false
        resetShipForm()
        getOrderList()
      } catch (error) {
        console.error('发货失败:', error)
        ElMessage.error('发货失败')
      } finally {
        shipSubmitting.value = false
      }
    }
  })
}

// 初始化
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  /* 让内容紧贴右侧 */
  min-width: 0;
}

.filter-container {
  margin-bottom: 20px;
}

.tabs-container {
  margin-top: 20px;
}

.orders-empty {
  text-align: center;
  color: #999;
  font-size: 16px;
  padding: 60px 0 40px 0;
  background: #fff;
  border-radius: 8px;
  min-height: 200px;
}

/* 订单商品信息样式 */
.order-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.item-info {
  flex: 1;
  min-width: 0;
  padding-right: 10px;
}

.item-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-spec {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.item-price {
  font-size: 13px;
  color: #666;
}

/* 价格样式 */
.price {
  color: #f56c6c;
  font-weight: bold;
}

/* 对话框样式 */
.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

/* 表格内容垂直居中 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

/* 状态标签样式 */
:deep(.el-tag) {
  margin: 0 2px;
}

/* 分页样式 */
.pagination-container {
  padding: 20px;
  text-align: right;
}
</style>